<template>
  <div class="mouse-interaction-sender">
    <div class="header">
      <span>内置鼠标交互</span>
      <div v-show="mouse_interaction" class="float-right">
        <a href="javascript:;" @click.stop="deleteMouseInteractionItem"><Icon type="md-trash" size="15"/></a>
        <a href="javascript:;" @click.stop="addMouseInteractionItem"><Icon type="md-add" size="15"/></a>
      </div>
      <div class="clearfix"></div>
    </div>
    <div v-if="mouse_interaction" class="body">
      <Tabs ref="mouseInteractionTabs" size="small">
        <TabPane :label="'交互'+(index+1)" v-for="(item, index) in mouse_interaction" :key="index" :style="{padding: '10px'}">
          <Form :label-width="80">
            <FormItem label="事件类型">
              <Select size="small" v-model="item.mouseType">
                <Option v-for="item in mouseTypesData" :value="item.value" :key="item.value">{{ item.label }}</Option>
              </Select>
            </FormItem>
            <FormItem label="动作">
              <Select size="small" v-model="item.action">
                <Option v-for="item in actions" :value="item.value" :key="item.value">{{ item.label }}</Option>
              </Select>
            </FormItem>
            <FormItemPanel title="目标" :style="{backgroundColor: '#424242'}">
              <Button class="float-right" size="small" type="default" @click="openWaitingTargetDrawer(item)">选择交互目标</Button>
              <div class="clearfix"></div>
              <div class="target-item" :title="'ID：'+targetItem.id" v-for="(targetItem, index2) in item.target" :key="index2">
                {{targetItem.name}}
                <a href="javascript:;" @click.stop="deleteMouseInteractionTargetItem(item, index2)"><Icon type="md-trash" /></a>
              </div>
            </FormItemPanel>
            <FormItem label="动画类型">
              <Select size="small" v-model="item.animationType">
                <Option v-for="item in animationTypes" :value="item.value" :key="item.value">{{ item.label }}</Option>
              </Select>
            </FormItem>
            <FormItem label="动画时长">
              <Tooltip content="设为0可以取消动画效果" placement="left">
                <InputNumber size="small" :max="1000000" :min="0" :step="100" v-model="item.animationDelay" :active-change="false"></InputNumber> ms
              </Tooltip>
            </FormItem>
          </Form>
        </TabPane>
      </Tabs>
      <p style="text-align: center; margin: 5px 0;" v-show="mouse_interaction.length == 0">点击 + 添加交互事件</p>
    </div>
    <div v-else class="not-stream-message">当前组件版本未支持鼠标交互，请升级组件</div>

    <Drawer title="选择交互目标"
            :width="330"
            placement="right"
            :closable="true"
            :mask-closable="false"
            :draggable="false"
            transfer
            v-model="waitingTargetDrawerVisible"
            @on-close="waitingTargetDrawerCloseHandler"
            :styles="$PnUtil.buildDrawerStyleByHasFooter()">
      <div class="m-b-10px">
        <Input v-model="searchValue" search enter-button clearable placeholder="输入名称或ID搜索"
               @on-search="searchWaitingTarget" @on-clear="searchWaitingTarget"/>
      </div>
      <div class="waiting-target-panel"
           :class="{
            'dashed-panel': !item.componentId && item.type != 'groupItem',
            'group-item-panel': item.type == 'groupItem',
            'layout-item-panel': item.type == 'layoutItem',
            'group-item-active': item.type == 'groupItem' && item.active,
            'layout-item-active': item.type == 'layoutItem' && item.active
           }"
           v-for="(item, index) in waitingTarget" :key="index"
           v-show="item.show"
           @mouseenter="itemMouseenterHandle(item)"
           @mouseleave="itemMouseleaveHandle" @click.stop="item.active = !item.active">
        <div class="float-left">
          {{item.name}}<br/>ID【{{item.id}}】
        </div>
        <div class="clearfix"></div>
      </div>
      <DrawerFooter>
        <Button class="m-r-5px" type="default" @click="closeWaitingTargetDrawer">关闭</Button>
        <Button class="m-r-5px" type="default" @click="clearWaitingTargetSelected"><Icon type="md-close" /> 清空选中</Button>
        <Button type="primary" @click="submitWaitingTargetSelected"><Icon type="md-checkmark" /> 提交选中</Button>
      </DrawerFooter>
    </Drawer>
  </div>
</template>

<script>
import _ from 'lodash'
import {createHelpers} from 'vuex-map-fields';

const {mapFields} = createHelpers({
  getterType: 'designer/getLayoutItem',
  mutationType: 'designer/updateLayoutItem',
});
export default {
  name: "MouseInteractionSender",
  props: {
    mouseTypes: {
      type: Array,
      required: true,
      default () {
        return []
      }
    }
  },
  data() {
    return {
      actions: [
        {label: '显示', value: 'show'},
        {label: '隐藏', value: 'hide'},
        {label: '显隐切换', value: 'toggle'}
      ],
      animationTypes: [
        {label: '默认', value: 'normal'},
        {label: '滑动', value: 'slide'},
        {label: '淡入淡出', value: 'fade'}
      ],
      currentSelectMouseInteractionItem: null, // 在点击选择目标时，临时存储当前选中的鼠标交互项
      waitingTarget: [], // 备选目标
      waitingTargetDrawerVisible: false,
      searchValue: ''
    }
  },
  mounted() {

  },
  methods: {
    addMouseInteractionItem () {
      this.mouse_interaction.push(this.$PnDesigner.buildMouseInteractionItem())
    },
    deleteMouseInteractionItem () {
      this.mouse_interaction.splice(this.$refs['mouseInteractionTabs'].activeKey, 1)
    },
    deleteMouseInteractionTargetItem (item, index) {
      item.target.splice(index, 1)
    },
    loadWaitingTarget () {
      this.waitingTarget = [];
      let allCompinfoObj = JSON.parse(localStorage.getItem('allCompinfoObj'));
      let allBelongGroupLayoutItemIds = [];
      let layoutGroup = this.$PnUtil.deepClone(this.$store.getters['designer/getLayoutGroup']);
      for (let i=0; i<layoutGroup.length; i++) {
        allBelongGroupLayoutItemIds = _.concat(allBelongGroupLayoutItemIds, layoutGroup[i].layoutItemIds)
        this.waitingTarget.push({
          type: 'groupItem',
          id: layoutGroup[i].id,
          name: layoutGroup[i].name ? layoutGroup[i].name : '组',
          active: false,
          show: true
        })
      }
      let layoutItems = this.$PnUtil.deepClone(this.$store.getters['designer/getLayoutItems'])
      for (let i=0; i<layoutItems.length; i++) {
        if (allBelongGroupLayoutItemIds.indexOf(layoutItems[i].id) == -1 && this.layoutItemId != layoutItems[i].id) {
          this.waitingTarget.push({
            type: 'layoutItem',
            id: layoutItems[i].id,
            name: layoutItems[i].aliasName ? layoutItems[i].aliasName : layoutItems[i].component.id ? allCompinfoObj[layoutItems[i].component.name].alias_name : '空布局块',
            componentId: layoutItems[i].component.id ? layoutItems[i].component.id : '',
            active: false,
            show: true
          })
        }
      }
      // 处理已选状态
      if (this.currentSelectMouseInteractionItem.target) {
        this.waitingTarget.forEach(item => {
          for (let i=0; i<this.currentSelectMouseInteractionItem.target.length; i++) {
            if (item.id == this.currentSelectMouseInteractionItem.target[i].id) {
              item.active = true
            }
          }
        })
      }
    },
    searchWaitingTarget () {
      this.waitingTarget.forEach(item => {
        if (item.name.indexOf(this.searchValue) > -1 || item.id.indexOf(this.searchValue) > -1) {
          item.show = true
        }else {
          item.show = false
        }
      })
    },
    openWaitingTargetDrawer (item) {
      this.waitingTargetDrawerVisible = !this.waitingTargetDrawerVisible;
      this.currentSelectMouseInteractionItem = item;
      this.loadWaitingTarget()
    },
    waitingTargetDrawerCloseHandler () {
      this.waitingTarget = []
    },
    closeWaitingTargetDrawer () {
      this.waitingTargetDrawerVisible = !this.waitingTargetDrawerVisible;
      this.waitingTarget = []
    },

    itemMouseenterHandle (item) {
      if (item.type == 'groupItem') {
        this.$store.commit('designer/setCurrentHoverGroupItemId', item.id)
      }else if (item.type == 'layoutItem') {
        this.$store.commit('designer/setCurrentHoverLayoutItemId', item.id)
      }
    },
    itemMouseleaveHandle () {
      this.$store.commit('designer/setCurrentHoverLayoutItemId', '')
      this.$store.commit('designer/setCurrentHoverGroupItemId', '')
    },

    clearWaitingTargetSelected () {
      for (let i=0; i<this.waitingTarget.length; i++) {
        this.waitingTarget[i].active = false
      }
    },
    submitWaitingTargetSelected () {
      this.currentSelectMouseInteractionItem.target = [];
      for (let i=0; i<this.waitingTarget.length; i++) {
        if (this.waitingTarget[i].active) {
          this.currentSelectMouseInteractionItem.target.push({
            type: this.waitingTarget[i].type == 'groupItem' ? 'groupItem' : 'layoutItem',
            id: this.waitingTarget[i].id,
            name: this.waitingTarget[i].name
          })
        }
      }
      this.waitingTarget = [];
      this.waitingTargetDrawerVisible = !this.waitingTargetDrawerVisible
    }
  },
  computed: {
    ...mapFields({

      layoutItemId: 'id',
      mouse_interaction: 'component.compConfigData.mouse_interaction'

    }),
    mouseTypesData () {
      let data = [
        {label: '鼠标单击', value: 'click'},
        {label: '鼠标滑入', value: 'mouseenter'},
        {label: '鼠标滑出', value: 'mouseleave'}
      ]
      return _.filter(data, (o) => {
        return this.mouseTypes.indexOf(o.value) > -1
      })
    }
  },
  watch: {}
}
</script>

<style lang="less" scoped>
.mouse-interaction-sender {
  background-color: #616161;
  border: 2px solid #424242;
  border-radius: 4px;
  margin-bottom: 10px;
  .header {
    height: 35px;
    line-height: 35px;
    padding: 0 10px;
    background-color: #2196f3;
    border-top-left-radius: 3px;
    border-top-right-radius: 3px;
    a {
      color: #fff;
      float: right;
      &:hover {
        color: #e0e0e0;
      }
    }
  }
  .body {
    .target-item {
      height: 25px;
      line-height: 25px;
      padding: 0 5px;
      background-color: #2196f3;
      margin-top: 5px;
      border-radius: 3px;
      a {
        color: #fff;
        float: right;
        &:hover {
          color: #e0e0e0;
        }
      }
    }
  }
  .not-stream-message {
    padding: 8px;
    text-align: center;
    color: #f44336;
  }
}
.waiting-target-panel {
  background-color: #424242;
  border-radius: 3px;
  padding: 7px;
  margin-bottom: 7px;
  cursor: pointer;
  font-size: 12px;
  &:hover {
    box-shadow: 0px 0px 5px #9e9e9e;
  }
  &.group-item-active {
    background-color: #fb8c00;
  }
  &.layout-item-active {
    background-color: #2196f3;
  }
  &.layout-item-panel {
    border: 1px solid #2196f3;
  }
  &.group-item-panel {
    border: 1px solid #fb8c00;
  }
  &.dashed-panel {
    border: 1px dashed #fafafa;
  }
  i {
    margin-top: 4px;
  }
}
</style>
